/*
 * Copyright (c) 2017. Visionet and/or its affiliates. All right reserved.
 * VISIONET PROPRIETARY/CONFIDENTIAL.
 */
package com.visionet.security.service.impl;

import com.visionet.jumper.core.exception.runtime.FrameworkException;
import com.visionet.jumper.core.service.impl.AbstractBaseService;
import com.visionet.jumper.utils.StringUtils;
import com.visionet.security.base.constants.Algorihtm;
import com.visionet.security.base.constants.Constants;
import com.visionet.security.base.enums.UserStatus;
import com.visionet.security.domain.dto.UserDTO;
import com.visionet.security.domain.entity.User;
import com.visionet.security.repository.UserRepository;
import com.visionet.security.service.UserService;
import com.visionet.security.utils.CodecUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author TC.Ubuntu
 * @since 2017/7/5.
 */
@Service
public class UserServiceImpl extends AbstractBaseService<User> implements UserService {

	@Resource
	private UserRepository userRepository;

	@Override
	public User findByLoginName(String loginName) {
		return userRepository.findByLoginName(loginName);
	}

	@Override
	public void addUser(UserDTO userDto) {
		if(StringUtils.isEmpty(userDto.getLoginName())){
			throw new FrameworkException("登陆名不能为空！");
		}
		if(StringUtils.isEmpty(userDto.getPassword())){
			throw new FrameworkException("用户密码不能为空！");
		}
		User user = new User();
		//加密前的盐
		String salt = Constants.SALT_BYTE;
		//加密后的盐
		String encodeSalt = CodecUtils.encodeHexString(salt.getBytes());
		//加密密码
		SimpleHash hash = new SimpleHash(Algorihtm.HASH_ALGORITHM, userDto.getPassword(),
				Constants.SALT_BYTE.getBytes(), Algorihtm.HASH_ITERATIONS);
		String encodedPassword = hash.toHex();

		BeanUtils.copyProperties(userDto, user);
		user.setPassword(encodedPassword);
		user.setSalt(encodeSalt);
		user.setStatus(UserStatus.AVAILABLE);
		this.save(user);
	}
}
